import 'package:flutter/material.dart';
import 'package:xh_danmu/xh_danmu.dart';

/// 简单文本弹幕组件 - 外部实现示例
class SimpleTextDanmuComponent extends XhDanmuComponent {
  final String text;
  final Color color;
  final double fontSize;
  final FontWeight fontWeight;
  final EdgeInsets padding;
  final BoxDecoration? decoration;

  // 缓存计算的宽度
  double? _cachedWidth;

  SimpleTextDanmuComponent({
    required String id,
    required this.text,
    this.color = Colors.white,
    this.fontSize = 16.0,
    this.fontWeight = FontWeight.w500,
    this.padding = const EdgeInsets.symmetric(horizontal: 6, vertical: 0), // 与buildWidget保持一致
    this.decoration,
    super.state = XhDanmuItemState.normal,
    super.clickable = false,
    super.extra,
  }) : super(id: id);

  @override
  double getWidth() {
    // 使用缓存避免重复计算
    if (_cachedWidth != null) {
      return _cachedWidth!;
    }

    // 计算文本宽度 - 使用基础字体大小，确保宽度计算稳定
    final textPainter = TextPainter(
      text: TextSpan(
        text: text,
        style: TextStyle(
          fontSize: fontSize, // 使用基础字体大小，不受状态影响
          fontWeight: fontWeight,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout();

    // 为文本添加一些额外空间，避免省略号
    _cachedWidth = textPainter.width + padding.horizontal + 4; // 额外增加4px空间

    return _cachedWidth!;
  }

  @override
  Widget buildWidget(
    BuildContext context,
    double maxHeight,
    VoidCallback? onTap,
    VoidCallback? onDoubleTap,
  ) {
    Widget textWidget = Container(
      width: getWidth(), // 使用计算的精确宽度
      height: maxHeight, // 强制使用轨道高度
      padding: padding, // 使用构造函数中的padding参数
      decoration: decoration ??
          BoxDecoration(
            color: Colors.black.withOpacity(0.6),
            borderRadius: BorderRadius.circular(4),
          ),
      child: Center(
        child: Text(
          text,
          style: TextStyle(
            color: _getStateColor(),
            fontSize: _getStateFontSize(),
            fontWeight: fontWeight,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );

    if (clickable && (onTap != null || onDoubleTap != null)) {
      textWidget = GestureDetector(
        onTap: () {
          onTapHandler();
          onTap?.call();
        },
        onDoubleTap: () {
          onDoubleTapHandler();
          onDoubleTap?.call();
        },
        child: textWidget,
      );
    }

    return textWidget;
  }

  /// 根据状态获取颜色
  Color _getStateColor() {
    switch (state) {
      case XhDanmuItemState.highlighted:
        return color.withOpacity(0.8);
      case XhDanmuItemState.clicked:
        return Colors.orange;
      case XhDanmuItemState.disabled:
        return color.withOpacity(0.3);
      case XhDanmuItemState.normal:
      default:
        return color;
    }
  }

  /// 根据状态获取字体大小
  double _getStateFontSize() {
    switch (state) {
      case XhDanmuItemState.highlighted:
        return fontSize * 1.1;
      case XhDanmuItemState.clicked:
        return fontSize * 1.2;
      case XhDanmuItemState.disabled:
        return fontSize * 0.9;
      case XhDanmuItemState.normal:
      default:
        return fontSize;
    }
  }

  @override
  void onTapHandler() {
    print('📝 文本弹幕被点击：$text');
  }

  @override
  void onDoubleTapHandler() {
    print('📝📝 文本弹幕被双击：$text');
  }
}

/// 自定义VIP弹幕组件示例
class VipDanmuComponent extends XhDanmuComponent {
  final String username;
  final String message;
  final int level;
  final String avatarUrl;

  VipDanmuComponent({
    required String id,
    required this.username,
    required this.message,
    required this.level,
    this.avatarUrl = '',
  }) : super(
          id: id,
          clickable: true,
          extra: {'type': 'vip'},
        );

  @override
  double getWidth() {
    // 精确计算VIP弹幕的实际宽度

    // 计算用户名文本宽度
    final usernameTextPainter = TextPainter(
      text: TextSpan(
        text: username,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 14,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    usernameTextPainter.layout();

    // 计算消息文本宽度
    final messageTextPainter = TextPainter(
      text: TextSpan(
        text: message,
        style: TextStyle(
          fontSize: 16,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    messageTextPainter.layout();

    // 计算等级文本宽度
    final levelTextPainter = TextPainter(
      text: TextSpan(
        text: 'Lv.$level',
        style: TextStyle(
          fontSize: 10,
          fontWeight: FontWeight.bold,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    levelTextPainter.layout();

    // 计算总宽度：图标 + 间距 + 用户名 + 间距 + 消息 + 间距 + 等级 + 内边距
    return 20 +
        8 +
        usernameTextPainter.width +
        8 +
        messageTextPainter.width +
        8 +
        (levelTextPainter.width + 12) +
        12; // 图标20px，外层容器内边距12px
  }

  @override
  Widget buildWidget(
    BuildContext context,
    double maxHeight,
    VoidCallback? onTap,
    VoidCallback? onDoubleTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      onDoubleTap: onDoubleTap,
      child: Container(
        height: maxHeight, // 强制使用轨道高度
        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0), // 减小内边距避免溢出
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.amber, Colors.orange],
          ),
          borderRadius: BorderRadius.circular(25),
          border: Border.all(color: Colors.amber, width: 2),
          boxShadow: [
            BoxShadow(
              color: Colors.orange.withOpacity(0.3),
              blurRadius: 8,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
          children: [
            // VIP徽章
            Container(
              width: 20,
              height: 20, // 减小图标尺寸
              decoration: BoxDecoration(
                color: Colors.red,
                shape: BoxShape.circle,
              ),
              child: Icon(Icons.star, color: Colors.white, size: 12),
            ),
            SizedBox(width: 8),

            // 用户名
            Text(
              username,
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 14,
              ),
            ),
            SizedBox(width: 8),

            // 消息内容
            Flexible(
              child: Text(
                message,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),

            // 等级标识
            Container(
              margin: EdgeInsets.only(left: 8),
              padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
              decoration: BoxDecoration(
                color: Colors.purple,
                borderRadius: BorderRadius.circular(12),
              ),
              child: Text(
                'Lv.$level',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 10,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void onTapHandler() {
    print('🌟 VIP弹幕被点击：$username - $message');
  }

  @override
  void onDoubleTapHandler() {
    print('🌟🌟 VIP弹幕被双击：关注了用户 $username');
  }
}

/// 自定义礼物弹幕组件
class GiftDanmuComponent extends XhDanmuComponent {
  final String gifterName;
  final String giftName;
  final int giftCount;
  final String giftIcon;

  GiftDanmuComponent({
    required String id,
    required this.gifterName,
    required this.giftName,
    required this.giftCount,
    this.giftIcon = '🎁',
  }) : super(
          id: id,
          clickable: true,
          extra: {'type': 'gift'},
        );

  @override
  double getWidth() {
    // 精确计算礼物弹幕的实际宽度

    // 计算送礼者名称宽度
    final gifterTextPainter = TextPainter(
      text: TextSpan(
        text: gifterName,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 16,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    gifterTextPainter.layout();

    // 计算"送出"文字宽度
    final sendTextPainter = TextPainter(
      text: TextSpan(
        text: '送出',
        style: TextStyle(
          fontSize: 14,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    sendTextPainter.layout();

    // 计算礼物信息宽度
    final giftTextPainter = TextPainter(
      text: TextSpan(
        text: '$giftName x$giftCount',
        style: TextStyle(
          fontSize: 14,
          fontWeight: FontWeight.bold,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    giftTextPainter.layout();

    // 计算总宽度：图标 + 间距 + 送礼者 + 间距 + "送出" + 间距 + 礼物信息容器 + 内边距
    final giftContainerWidth = giftTextPainter.width + 16; // 礼物信息容器的内边距
    return 20 +
        8 +
        gifterTextPainter.width +
        8 +
        sendTextPainter.width +
        8 +
        giftContainerWidth +
        12; // 图标20px，外层容器内边距12px
  }

  @override
  Widget buildWidget(
    BuildContext context,
    double maxHeight,
    VoidCallback? onTap,
    VoidCallback? onDoubleTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      onDoubleTap: onDoubleTap,
      child: Container(
        height: maxHeight, // 强制使用轨道高度
        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 0), // 减小内边距避免溢出
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.pink, Colors.purple],
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
          ),
          borderRadius: BorderRadius.circular(25),
          border: Border.all(color: Colors.white, width: 2),
          boxShadow: [
            BoxShadow(
              color: Colors.purple.withOpacity(0.4),
              blurRadius: 12,
              offset: Offset(0, 4),
            ),
          ],
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
          children: [
            // 礼物图标
            Text(giftIcon, style: TextStyle(fontSize: 20)), // 减小图标尺寸
            SizedBox(width: 8),

            // 送礼者名称
            Text(
              gifterName,
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
            ),
            SizedBox(width: 8),

            // 送出文字
            Text(
              '送出',
              style: TextStyle(
                color: Colors.white70,
                fontSize: 14,
              ),
            ),
            SizedBox(width: 8),

            // 礼物名称和数量
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Text(
                '$giftName x$giftCount',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void onTapHandler() {
    print('🎁 礼物弹幕被点击：$gifterName 送出 $giftName x$giftCount');
  }

  @override
  void onDoubleTapHandler() {
    print('🎁🎁 礼物弹幕被双击：感谢 $gifterName 的礼物！');
  }
}

/// 系统通知弹幕组件
class SystemNoticeDanmuComponent extends XhDanmuComponent {
  final String title;
  final String content;
  final IconData icon;
  final Color backgroundColor;

  SystemNoticeDanmuComponent({
    required String id,
    required this.title,
    required this.content,
    this.icon = Icons.notifications,
    this.backgroundColor = Colors.blue,
  }) : super(
          id: id,
          clickable: false,
          extra: {'type': 'system_notice'},
        );

  @override
  double getWidth() {
    // 精确计算系统通知的实际宽度

    // 计算标题文本宽度
    final titleTextPainter = TextPainter(
      text: TextSpan(
        text: title,
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 14,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    titleTextPainter.layout();

    // 计算内容文本宽度
    final contentTextPainter = TextPainter(
      text: TextSpan(
        text: content,
        style: TextStyle(
          fontSize: 12,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    contentTextPainter.layout();

    // 计算合并文本的宽度
    final combinedTextPainter = TextPainter(
      text: TextSpan(
        text: '$title: $content',
        style: TextStyle(
          fontWeight: FontWeight.bold,
          fontSize: 12,
        ),
      ),
      textDirection: TextDirection.ltr,
    );
    combinedTextPainter.layout();

    // 计算总宽度：图标 + 间距 + 合并文本 + 内边距
    return 16 + 8 + combinedTextPainter.width + 12; // 图标16px，间距8px，内边距12px
  }

  @override
  Widget buildWidget(
    BuildContext context,
    double maxHeight,
    VoidCallback? onTap,
    VoidCallback? onDoubleTap,
  ) {
    return Container(
      height: maxHeight, // 强制使用轨道高度
      padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4), // 调整内边距
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.white, width: 1),
        boxShadow: [
          BoxShadow(
            color: backgroundColor.withOpacity(0.3),
            blurRadius: 8,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.center, // 垂直居中
        children: [
          // 系统图标
          Icon(icon, color: Colors.white, size: 16), // 减小图标尺寸
          SizedBox(width: 8),

          // 内容区域 - 简化为单行显示
          Flexible(
            child: Text(
              '$title: $content', // 合并标题和内容为一行
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 12, // 减小字体
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }
}
